/*var a=1;
function fun1(arg) {
	arg=2;
}
fun1(a);
console.log(a);


var o={
	a:1,
	b:2
};
function fun2(arg) {
	arg.a=3;
}
fun2(o);
console.log(o);*/


/*function fun(arg) {
		if (arg>100) {
		throw"you are sb"
	}
}
try{
	fun(150)
}catch(e){
	console.log(e)
}*/


/*var http = require('http');//包含加载http
var port = 80
var ip="127.0.0.1"
http.createServer(function (request, response) {
	
	// 发送 HTTP 头部 
	// HTTP 状态值: 200 : OK
	// 内容类型: text/plain
	//response.writeHead(200, {'Content-Type': 'text/html'});
	response.statusCode=200;
	response.setHeader("Content-Type","text/html")
	var fs=require("fs")
	var date=fs.readFileSync('"."+request.url')//读取某个文件

	response.end(date);
}).listen(port);
console.log('Server running at http://%s:%s/',ip,port);*/

var http = require('http');//包含加载http
var fs=require("fs")
var url=require("url")
var util=require("util")
var port = 80
var ip="127.0.0.1"
var sitename="Thh.messageboerd"
http.createServer(function (request, response) {
	
	// 发送 HTTP 头部 
	// HTTP 状态值: 200 : OK
	// 内容类型: text/plain
	//response.writeHead(200, {'Content-Type': 'text/html'});
	response.statusCode=200;
	response.setHeader("Content-Type","text/html")
	var date="404";
	/*if (request.url=='/index.html') {
		date+=fs.readFileSync('index.html')
	}else if (request.url=='/about.html') {
		date+=fs.readFileSync('about.html')
	}*/
	var ext=request.url.substr(-3,3)
	/*if (ext=='css') {
		response.setHeader("Content-Type","text/css")
	}else if(ext=='png'){
		response.setHeader("Content-Type","image/png")	
	}*/
	var exts={
		'css':'text/css',
		'png':'image/png',
		'js':'text/javascript',
	}
	/*if (exts[ext]==null) {
		exts[est]="text/plain"
	}*/
	response.setHeader("Content-Type",'exts[ext]')

	var p = url.parse(request.url,true);
	if (p.pathname=="/index.html") {
		try{
			date=fs.readFileSync("."+request.url,'utf-8')//返回的也是字符串
			date=date.replace(/%title/g,sitename)
			item = fs.readFileSync('data.json','utf8');
			item = JSON.parse(item);
			
			var s="";
		for (var i =0;i<item.length;i++) {//for
			s+= '<div class="item">'
			s+=	'<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>'
			s+=	'<p>'+item[i].message+'</p>'
			s+=	'</div>'
		}
		date=date.replace(/%main/g,s)
		
		}catch(e){
			console.log(e)
		}
	}else if (p.pathname=="/form.html") {
		date=fs.readFileSync("."+request.url,'utf-8')
	}else if (p.pathname=="/addmessage") {
		author=p.query.author;//取true的
		message=p.query.message;
		item =JSON.parse(fs.readFileSync('data.json','utf8')) ;
		item.push({					//解析字符串
			"author":author,
			"message":message,
			"time":new Date()
		})
		item=JSON.stringify(item);//将item对象转化为字符串
		fs.writeFileSync('data.json',item)
		date="提交成功";
		response.writeHead(302,{
			"Location":"/index.html"
		})
	}
	//date=util.format(date,sitename)//否则就有两个标题
		response.end(date);
	}).listen(port);
	console.log('Server running at http://%s:%s/',ip,port);
